<template>
	<view>
		<uv-popup ref="popup" mode="bottom" @maskClick="close" zIndex="99" :round="20" :safeAreaInsetBottom="false">
			<view class="safeBottom">
				<view class="right actived">
					<uv-icon name="close-circle" @click="close" :color="app.globalData.primaryColor"
						size="28"></uv-icon>
				</view>
				<view class="p-20" v-if="load">
					<uv-skeletons loading :skeleton="skeleton"></uv-skeletons>
					<scroll-view scroll-y class="scroll" style="height: 400px;">
						<uv-skeletons loading :skeleton="skeletonLine"></uv-skeletons>
					</scroll-view>
				</view>
				<view class="p-10" v-else>
					<view class="flex skuTop">
						<image class="card-image actived" :src="data.good.imagePath"
							@click="showPreview(data.good.imagePath)" lazy-load observeLazyLoad />
						<view class="column ellipsis">
							<view v-if="app.globalData.type">
								<view class="category">
									¥
									<view class="num">
										{{ data.good.price }}
									</view>
									<view v-if="!goodsItem">/起</view>
								</view>
							</view>
							<view class="category" v-else-if="!app.globalData.type && !goodsItem">
								¥
								<view class="num">
									{{ minprice }}
								</view>
								-
								¥
								<view class="num">
									{{ maxprice }}
								</view>
								/天
							</view>
							<view v-else>
								<view class="category">
									¥
									<view class="num">
										{{ data.good.price }}
									</view>
									/天
								</view>
								<view class="category">
									到期买断款 ¥{{ goodsItem && goodsItem[0]?.finishedprice }}
								</view>
							</view>
							<view class="category ellipsis black">
								<view class="nowrap">已选:</view>
								<view class="ellipsis">{{ selectSkuListString.filter(p => p.trim() !== '').toString() }}
								</view>
							</view>
						</view>
					</view>
					<scroll-view scroll-y class="scroll" :style="{ height: height + 'px' }">
						<view class="column g-7 m-10">
							<template v-for="(sku, index) in data.sku">
								<view class="group">{{ sku.name }}</view>
								<view class="radio-group">
									<view class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in sku.list"
										:key="item.value" @click="selectSku(item, sku.list, sku)">
										<!-- <view :class="['radio', item.active ? 'active' : 'default actived']">{{ item.name }}</view> -->
										<view class="radio" :style="activeStyle(item.active)">{{ item.name }}</view>
									</view>
								</view>
							</template>
							<!-- <view class="sku">
								<view class="sku-title">
									租机权益
								</view>
								<view class="sku-skus">
									<view v-for="item in quanYi" class="flex g-4 f-12">
										<uv-icon name="checkmark-circle" color="#c98f27" />
										{{ item }}
									</view>
								</view>
							</view> -->
						</view>
					</scroll-view>
				</view>
				<view class="btn">
					<uv-button v-if="userInfo&&userInfo.phone" text="立即购买" @click="buy" type="error" shape="circle"
						:color="app.globalData.primaryColor"></uv-button>
					<!-- #ifdef MP-WEIXIN -->
					<uv-button v-else text="立即购买" type="error" open-type="getPhoneNumber" shape="circle"
						:color="app.globalData.primaryColor" @getphonenumber="wechatLogin"></uv-button>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<uv-button v-else text="立即购买" @click="toLogin" shape="circle"
						:color="app.globalData.primaryColor"></uv-button>
					<!-- #endif -->
				</view>
			</view>
		</uv-popup>
		<uv-toast ref="toastRef" />
	</view>
</template>
<script setup>
	import {
		ref,
		reactive,
		onMounted,
		watch,
		watchEffect
	} from "vue";
	import {
		onShow
	} from '@dcloudio/uni-app'
	const height = uni.getSystemInfoSync().windowHeight / 1.5;
	const app = getApp()
	const userInfo = ref(null)
	onShow(() => {
		userInfo.value = uni.getStorageSync("userInfo")
	})
	const skeleton = [{
		type: 'flex',
		num: 1,
		children: [{
			type: 'custom',
			num: 1,
			style: 'width:70px;height:70px;marginRight: 20rpx;'
		}, {
			type: 'line',
			num: 2,
			gap: '30rpx',
			style: ['width: 150px;height: 20px;margin-top: 10px;margin-left: 10px;',
				'width: 30px;margin-left: 10px;',
			]
		}]
	}]
	const skeletonLine = [{
		type: 'line',
		num: 10,
		gap: '10px',
		style: ['width: 70px;height: 30px;margin-top: 10px;', 'height: 30px;', 'width: 50px;height: 30px;',
			'height: 30px;', 'width: 70px;height: 30px;', 'height: 30px;', 'width: 120px;height: 30px;',
			'height: 30px;', 'width: 70px;height: 30px;', 'height: 100px;'
		],
	}]
	const quanYi = ref([
		'终身质保包修/包换',
		'碎屏进水一年内保修一次',
		'配件四件套(壳膜数据线充电头)',
		'两年内免费更换一次原装电池',
	])
	const goods = ref({})
	const data = reactive({
		sku: [],
		good: {},
		imagePathMap: [],
	});
	const group = "保障服务（推荐选购）"
	const load = ref(true)
	const selectSkuListString = ref([])
	// 处理商品数据
	const setData = (value) => {
		const {
			sku,
			good,
			imagePathMap
		} = value;
		const handleOtherspecs = () => {
			if (goods.value.screen_price > 0 || goods.value.charger_price > 0) {
				const list = [];
				let checked = [0, 0];

				if (goods.value.screen_price > 0) {
					const name = `碎屏保障（${goods.value.screen_price}元）`
					list.push({
						check: true,
						group,
						name,
						show: true,
						active: true,
						disable: false,
					});
					checked[0] = 1;
					selectSkuListString.value[sku.length] = name.trim();
				}

				if (goods.value.charger_price > 0) {
					const name = `正品配件-充电器（${goods.value.charger_price}元）`
					list.push({
						check: true,
						group,
						name,
						show: true,
						active: false,
						disable: false,
					});
					// checked[1] = 1;
					// selectSkuListString.value[sku.length+1] = name.trim();
				}

				return [{
					name: group,
					multiple: true,
					checked,
					list
				}];
			}
			return [];
		};
		data.good = good
		data.sku = sku?.map((s) => ({
			...s,
			list: s.list.map((e) => ({
				...e,
				active: false,
				disable: !e.show
			})),
		})).concat(handleOtherspecs());
		load.value = false
	}
	// 计算价格范围
	const minprice = ref(0)
	const maxprice = ref(0)

	// 计算最低和最高价格
	const setPrice = (data_items) => {
		if (data_items) {
			const sellingArr = JSON.parse(data_items)
				.map(item => {
					return item[0].selling;
				})

			minprice.value = Math.floor(Number(Math.min.apply(Math, sellingArr)) * 100) / 100;
			maxprice.value = Math.floor(Number(Math.max.apply(Math, sellingArr)) * 100) / 100;
		}
	}
	// 商品详情弹窗引用
	const popup = ref(null);
	// 打开商品详情弹窗并设置数据
	const toLogin = () => {
		app.vibrate()
		uni.navigateTo({
			url: '/pages/login/login'
		})
	}
	const open = (value) => {
		popup.value.open()
		goods.value = value
		if (load.value && value) {
			setData({
				good: {
					imagePath: value.cover,
					price: app.globalData.type ? value.price_market : value.price_selling, //(商城和租赁的价格)
					skuId: value.code,
					name: value.name,
				},
				sku: value.specs
			})
			setPrice(value.data_items)
		}
	}
	// 切换规格类目
	const selectSkuList = ref([]);
	const goodsItem = ref(null)
	// 规格选择逻辑
	const selectSku = (value, list, parentSku) => {
		app.vibrate()
		if (value.active && !parentSku.multiple) return
		const sku = data.sku
		const parentIndex = sku.findIndex(p => p.name == parentSku.name)

		list?.map((item, index) => {
			if (parentSku.multiple) { //在这处理多选
				if (item.name == value.name) {
					item.active = !item.active;
					parentSku.checked[index] = item.active ? 1 : 0
					selectSkuListString.value[parentIndex + index] = item.active ? value.name.trim() : '';
				}
			} else {
				item.active = item.name == value.name;
				selectSkuListString.value[parentIndex] = value.name.trim();
			}
		})
		console.log('000999')
		if (parentSku.name != group) {
			const specs = goods.value.specs
			// const parentIndex = specs.findIndex(p => p.name == parentSku.name)
			selectSkuList.value[parentIndex] =
				`${parentSku.name}::${value.name}${(parentIndex + 1) === specs.length ? "" : ";;"}`;
			const skuString = selectSkuList.value.toString().replace(/,/g, "")
			goodsItem.value = JSON.parse(goods.value.data_items).find(p => p[0].key == skuString)
			console.log(goodsItem.value, "goodsItem");
			goodsItem.value && (data.good.price = app.globalData.type ? goodsItem.value[0]?.market : goodsItem.value[0]
				?.selling)
		}
	}
	// 购买相关逻辑
	const loading = ref(false)
	const buy = app.throttle((e) => {
		app.vibrate()
		const sku = goods.value.specs.map(item => {
			return item.name
		})
		const result = sku.filter(item1 => selectSkuList.value.every(item2 => !item2.includes(item1)));
		if (result.length !== 0) {
			showToast("请选择:" + result.toString())
			return false
		}
		loading.value = true
		// console.log(data.sku, group, data.sku.find(p => p.name == group), '999111')
		const otherChecked = data.sku.find(p => p.name == group)?.checked.map(p => "**" + p)
		const skuString = [data.good.skuId + '@'] + selectSkuList.value.concat(['@1']).concat(otherChecked)
			.toString().replace(/,/g, "")
		add(skuString)
	});
	const add = (items) => {
		app.post('api.auth.order/add', {
			items,
			with_admin_id: goods.value.with_admin_id
		}).then(res => {
			loading.value = false
			app.globalData.type ? toResults(res.order_no) : toOrderDetail(res.order_no)
		}).catch(error => {
			loading.value = false
		})
	}
	const toResults = (order_no) => {
		uni.redirectTo({
			url: '/pages/results/results?order_no=' + order_no,
		})
	}
	const toOrderDetail = (order_no) => {
		uni.navigateTo({
			url: '/pages/orderDetail/orderDetail?order_no=' + order_no,
			events: {
				close
			},
		})
	}
	const emit = defineEmits(["showPreview"]);
	const showPreview = (value) => {
		emit("showPreview", 0, [value]);
	}
	// 关闭商品规格弹框
	const close = () => {
		app.vibrate()
		popup.value.close()
	};
	// 输出组件的方法，让外部组件可以调用
	defineExpose({
		open,
	})
	const toastRef = ref(null)
	const showToast = (message, type = 'default') => {
		toastRef.value?.show({
			type,
			message,
			"z-index": 2000,
			duration: 2000
		})
	}

	const activeStyle = (bool) => {
		const defaultStyle = {
			backgroundColor: '#f2f2f2',
			border: '1px solid #f2f2f2'
		}
		const activeStyle = {
			backgroundColor: uni.$uv.colorToRgba(app.globalData.primaryColor, 0.32),
			border: '1px solid ' + app.globalData.primaryColor
		}
		return bool ? activeStyle : defaultStyle
	}

	//微信登录
	const wechatLogin = (e) => {
		console.log(e)
		uni.login({
			success: (res) => {
				if (res.errMsg == 'login:ok' && e.errMsg == 'getPhoneNumber:ok') {
					uni.getUserInfo({
						success: function(infoRes) {
							let nickName = infoRes.userInfo.nickName;
							let avatarUrl = infoRes.userInfo.avatarUrl;
							let req = {
								code: res.code,
								phone_code: e.code,
								nickName: infoRes.userInfo.nickName,
								avatarUrl: infoRes.userInfo.avatarUrl
							}
							app.post('api.Wechatapp/login', req).then(loginRes => {
								userInfo.value = loginRes
								uni.setStorageSync("userInfo", loginRes)
								buy();
							})
						}
					})
					buy()
				}
			},
			fail(msg) {}
		})
	}
</script>

<style scoped>
	.safeBottom {
		padding-bottom: env(safe-area-inset-bottom);
	}

	.right {
		position: absolute;
		z-index: 99;
		top: 10px;
		right: 10px;
	}

	.skuTop {
		width: 100%;
		box-shadow: 0 0.4px 0 rgba(18, 22, 33, .12);
	}

	.g-7 {
		gap: 7px
	}

	.m-10 {
		margin: 0 10px;
	}

	.radio-group {
		display: flex;
		gap: 10px;
		flex-wrap: wrap;
	}

	.group {
		width: -webkit-fill-available;
		margin-top: 10px;
		font-weight: 600;
		font-size: 14px;
	}

	.radio {
		border-radius: 20px;
		padding: 8px 16px;
		font-size: 11px;
	}

	.active {
		background-color: hsla(18, 85%, 68%, 0.302);
		border: 1px solid #f39066;
	}

	.default {
		background-color: #f2f2f2;
		border: 1px solid #f2f2f2;
	}

	.hidden {
		display: none;
	}
</style>

<style lang="scss" scoped>
	::v-deep {
		.uv-popup {
			z-index: 99 !important;
		}
	}

	.bottom {
		background-color: transparent !important;
		height: -webkit-fill-available;

		::v-deep.scroll,
		scroll-view {
			width: -webkit-fill-available;
			height: 400px;
		}
	}

	// .btn {
	//   position: relative !important;
	//   bottom: 0 !important;
	// }

	.cardTitle {
		width: 100%;
		font-size: medium;
		font-weight: 600;
	}

	.card {
		background-color: #f2f2f2;
		margin: 0 10px;
		box-shadow: 0 1px 7px 0 #edeef1;
		padding: 10px;
		--nut-cell-background: transparent;
	}

	.card-image {
		flex-shrink: 0;
		width: 70px;
		height: 70px;
		border-radius: 6px;
	}

	.category {
		text-transform: uppercase;
		font-size: 11px;
		font-weight: 600;
		color: red;
		padding: 4px 10px;
		display: flex;
		align-items: baseline;
	}

	.category .num {
		font-size: 20px;
		font-weight: 900;
		line-height: 2px;
		margin: 2px;
	}

	.category:hover {
		cursor: pointer;
	}

	.p-10 {
		padding: 10px 10px 60px;
	}

	.p-20 {
		padding: 10px 20px 60px;
	}

	.flex {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.center {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.align-center {
		display: flex;
		align-items: center;
		font-weight: bold;
	}

	.between {
		justify-content: space-between;
	}

	.grow {
		flex-grow: 1;
	}

	.g-10 {
		gap: 10px;
	}

	.h-30 {
		height: 30px;
	}

	.h-100 {
		height: 100px;
	}

	.end {
		place-self: flex-end;
	}

	.ant-grid {
		width: 100%;
	}

	.ant-button {
		width: 100%;
		border-radius: 30px;
	}

	.ant-container {
		margin-bottom: 0;
	}

	.round {
		border-radius: 50px;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
		color: black;
	}

	.black {
		color: black;
	}

	.weight {
		font-weight: 700;
	}

	.size {
		font-size: small;
		-webkit-line-clamp: 3;
	}

	.status {
		color: orange;
		font-weight: blod;
	}

	.fontLong {
		-webkit-box-orient: vertical;
		display: -webkit-box;
		word-break: break-all;
	}

	.ant-tabs-content {
		margin: 10px;
		border-radius: 10px;
	}

	.yajin {
		width: 120px;
		text-align: center;
		background-color: #f5f5f5;
	}

	.ant-list-item {
		font-size: 10px;
	}

	.ant-list-item-line {
		padding: 5px;
	}

	.bottom {
		width: -webkit-fill-available;
		padding: 10px;
		gap: 10px;
		display: flex;
		flex-direction: column;
		bottom: env(safe-area-inset-bottom);
		position: fixed;
		background-color: whitesmoke;
		box-shadow: 0 0 10px rgb(237, 238, 241);
		backdrop-filter: blur(10px);
	}
</style>

<style lang="scss" scoped>
	.sku-title {
		height: 13px;
		margin: 10px 0;
		font-size: 13px;
		font-weight: bold;
		color: #000;
	}

	.sku-skus {
		background: linear-gradient(180deg, #fcf9ee, white);
		border-radius: 20px;
		padding: 10px;
		display: flex;
		flex-direction: column;
		gap: 10px;
	}

	.f-12 {
		font-size: 12px;
	}
</style>